#!/bin/bash
# -*- coding: UTF-8 -*-
# vim:ts=4:sw=4:ai:si:ci

# mailtest.sh - Tests your smtp mail by sending something and parsing errors
# Copyright 2006 Eliphas Levy Theodoro <mailto: lookup on euodeio.net>
# License: GPLv2
# keywords: bash script tcp smtp send mail

# ChangeLog
# 2005-07-04: v0.1
#   First version, release

mailserver=smtp.example.com
mailport=25
from="me@example.com"
to="you@example.com"
subject="My shell script sent you an email"

# The text can be in various lines, but you NEED to use \r\n.
# Some servers (qmail mostly) will not accept it otherwise.
# http://www.faqs.org/rfcs/rfc2822.html 
# Note: You can hack into this and use some file if you like.
text="I'm sending you an e-mail.\r
It's beautiful, isn't?\r
.\r\n"

exec 5<>/dev/tcp/$mailserver/$mailport
quit() {
    echo "Closing connection."
    exec 5<&- # closing connection
}
# ensure closed connection on end
trap quit EXIT
trap quit SIGHUP
trap quit SIGINT
trap quit SIGQUIT
trap quit SIGKILL

date=`LC_ALL=C date "+%a, %d %b %Y %k:%M:%S %z"`
header="From: $from\r\nTo: $to\r\nSubject: $subject\r\nDate: $date\r\n\r\n"

i=0
exitcode=0
while read line; do
    # you can see everything the server echoes by uncommenting this:
    # echo "$line"
    set - $line
    case $1 in
    220) # greeting, we're in
        echo "Great, server is showing confidence."
        echo "EHLO $HOSTNAME" >&5
        ;;
    250)
        let i++
        if [ "$i" == 1 ]; then # we've been greeted, let's say what we want
            echo "Sending recipient address"
            echo -en "mail from: $from\r\n" >&5
        elif [ "$i" == 2 ]; then # final destination
            echo "Sending destination address"
            echo -en "rcpt to: $to\r\n" >&5
        elif [ "$i" == 3 ]; then # data starting... now!
            echo "Starting data transfer"
            echo -en "data\r\n" >&5
        elif [ "$i" == 4 ]; then # data successfully received
            echo "All done, goodbye friend"
            echo -en "quit\r\n" >&5
        else # we don't expect more than 3 250-OK responses.
            echo "I can't understand you, insensitive clod!"
            echo -en ".\r\nrset\r\nquit\r\n" >&5
            exitcode=1;break
        fi
        ;;
    354) # go ahead, send text
        echo "Email header going"
        echo -en "$header" >&5
        echo "Email body going"
        echo -en "$text" >&5
        ;;
    [0-9]*-*) # followup lines, don't bother
        true
        ;;
    221) # thanks! by the way, nice shoes.
        echo "Thanks, see you again"
        true
        ;;
    *) # whoops, something happened .
        echo "Error sending mail:"
        echo "$line"
        echo -en ".\r\nrset\r\nquit\r\n" >&5
        exitcode=1;break
        ;;
    esac
done <&5
quit
exit $exitcode
